package top.maof.book.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.maof.book.model.Role;
import top.maof.book.model.UserRole;
import top.maof.book.result.ApiResponse;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.service.UserRoleService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 久念
 * @date 2022/03/03 19:37
 */
@Api(tags = "userRole")
@RestController
@RequestMapping("/userRole")
@RequiresRoles({Role.ADMIN})
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    @ApiOperation("新建")
    @PostMapping("/create")
    public ApiResponse create(@RequestBody UserRole userRole) {
        return ApiResponse.success(userRoleService.create(userRole));
    }

    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable Integer id) {
        userRoleService.deleteById(id);
        return ApiResponse.success(null);
    }

    @ApiOperation("批量删除")
    @GetMapping("/delete/batch")
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String[] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        userRoleService.deleteByIdInBatch(idList);
        return ApiResponse.success(null);
    }

    @ApiOperation("根据ID修改")
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody UserRole userRole) {
        userRoleService.updateById(userRole);
        return ApiResponse.success(null);
    }

    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse<PageData<UserRole>> findPage(@RequestBody PageWrap<UserRole> pageWrap) {
        return ApiResponse.success(userRoleService.findPage(pageWrap));
    }

    @ApiOperation("根据ID查询")
    @GetMapping("/{id}")
    public ApiResponse findById(@PathVariable Integer id) {
        return ApiResponse.success(userRoleService.findById(id));
    }
}
